<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="100px"
             status-icon>

      <el-form-item label="名称：" prop="name">
        <el-input v-model="formData.name" :readonly="readonly" maxlength="64" placeholder="请输入名称" show-word-limit/>
      </el-form-item>

      <el-form-item label="管理者：">
        <SelectRemote v-if="!readonly" v-model="managerAccount" api-url="/search/user/list" placeholder="请输入用户账号进行选择" @change="handleSelectChange" style="margin-bottom: 8px;width: 60%"/>
        <el-select v-model="managerIds" multiple>
          <el-option v-for="item in managerList" :key="item.uid" :label="item.account" :value="item.uid"/>
        </el-select>
      </el-form-item>

      <el-form-item label="备注：">
        <el-input v-model="formData.remark" :readonly="readonly" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>

    <template v-if="formData.id > 0">
      <el-divider border-style="dashed"/>

      <el-table :data="storeList" fit highlight-current-row>
        <el-table-column prop="id" align="center" label="门店编号" min-width="120">
        </el-table-column>

        <el-table-column prop="cover_url" align="center" label="门店封面" min-width="120">
          <template #default="scope">
            <el-popover v-if="isImageUrl(scope.row.cover_url)" placement="left" style="text-align: center;" trigger="hover" width="">
              <template #reference>
                <img :alt="scope.row.cover_url" :src="scope.row.cover_url" style="height: 21px;max-width: 130px;">
              </template>
              <img :src="scope.row.cover_url" style="max-width: 220px;">
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column prop="name" align="center" label="门店名称" min-width="300">
        </el-table-column>
      </el-table>
    </template>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['store:alliance:create', 'store:alliance:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { StoreAlliance, storeAllianceInfo, StoreManager, storeAllianceSaveOrUpdate } from '@/api/api-store.ts';
import { StoreData } from '@/api/common.ts';
import { isImageUrl } from '@/utils/is.ts';
import { SelectRemote } from '@/components/other';

defineOptions({name: 'store-alliance-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

/** 默认表单数据 */
const defaultForm: StoreAlliance = <StoreAlliance>{id: 0};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

/** 门店列表 */
const storeList = ref<StoreData[]>([]);
/** 门店管理者列表 */
const managerList = ref<StoreManager[]>([]);
const managerIds = ref<number[]>([])
const managerAccount = ref();

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '门店联盟配置';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await storeAllianceInfo(id)
      formData.value = data.info;
      managerList.value = JSON.parse(formData.value.managers) || [];
      managerIds.value = managerList.value.map(item => item.uid);
      storeList.value = data.list || [];
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 设置门店管理者
    formData.value.managers = JSON.stringify(managerList.value.filter(it => managerIds.value.includes(it.uid)));
    // 提交数据
    storeAllianceSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  storeList.value = [];
  managerList.value = [];
  managerIds.value = [];
  managerAccount.value = undefined;
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 用户选择被改变 */
const handleSelectChange = (val: any) => {
  if (val && val.id && !managerList.value.find(it => it.uid == val.id)) {
    managerList.value.push({uid: val.id, account: val.label1});
    managerIds.value.push(val.id);
  }
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-input-number {
    max-width: 13rem;
  }
}
</style>
